/**
 * 2010(c) www.jcaramel.com
 * MENU
 * 
 * Requires
 * 	jCaramel-Core
 */

jCaramel.toolbar = {
	
	/**
	 * Creates the toolbar
	 * @param {jQuery} tb UL to convert into toolbar
	 * @param {Object} settings Settings of toolbar creation
	 */
	_create: function(tb, settings){
		
		//Create handle
		jCaramel.createHandle(tb);
		
		//Add the class to the UL
		tb.addClass('toolbar');
		
		//Hide nested lists
		tb.children('li').find('ul').hide();

		//Set the orientation of the toolbar
		jCaramel.toolbar.orientation(tb, settings.orientation);
			
		//Assign event handlers
		jCaramel.toolbar.assignItemHandlers(tb.children('li'));
		
		//Prep top level
		jCaramel.toolbar.prep(tb, tb.children('li'));
	},
	
	/**
	 * Assigns hanlders to items (buttons)
	 * @param {jQuery} items
	 */
	assignItemHandlers: function(items){
		items
			.unbind('mouseenter', jCaramel.toolbar.item_MouseEnter)
			.mouseenter(jCaramel.toolbar.item_MouseEnter)
			
			.unbind('mousleave', jCaramel.toolbar.item_MouseLeave)
			.mouseleave(jCaramel.toolbar.item_MouseLeave)
	},
	
	/**
	 * Handles click on items
	 * @param {Object} evt
	 */
	item_Click: function(evt){
		item = jQuery(this);
		
		//TODO: display menu
	},
	
	/**
	 * Handles MouseEnter event of items
	 * @param {jQuery} evt
	 */
	item_MouseEnter: function(evt){
		jQuery(this).addClass('selected');
	},
	
	/**
	 * Handles MouseLeave event of items
	 * @param {jQuery} evt
	 */
	item_MouseLeave: function(evt){
		jQuery(this).removeClass('selected');	
	},
	
	
	/**
	 * Sets or gets the orientation of the specified toolbar
	 * @param {jQuery} tb Toolbar
	 * @param {string} orientation 'horizontal' or 'vertical'
	 */
	orientation: function(tb, orientation){
		
		//Set orientation
		tb.tag('orientation', orientation);
		
		tb
			.removeClass('toolbar-horizontal')
			.removeClass('toolbar-vertical')
			.addClass('toolbar-' + orientation);
			
	},
	
	/**
	 * 
	 * @param {Object} items
	 */
	prep: function(tb, items){
		//Check for dropdowns
		items.each(function(index){
			var li = jQuery(this);
			var ul = li.children('ul');
			
			if(ul.size() == 1){
				li.append( jQuery('<div>').addClass('glyph-16 glyph-dropdown') );
			}
			
		});
	},
	
};

/**
 * Makes the element a toolbar
 * @param {Object} a
 * @param {Object} b
 * @param {Object} c
 */
jQuery.fn.toolbar = function(a, b, c){
	
	if (typeof(a) == 'string') {
		return jCaramel.toolbar[a](this, b);
	}
	else {
		settings = jQuery.extend({
			
			orientation: 'horizontal',
			
			draggable: false,
			
			hidable: false,
			
			text: '',
			
		}, a);
		
		//Create the listview
		jCaramel.toolbar._create(this, settings);
		
		return this;
	}
};
